/**
 *  上传文件相关
 *  Created by lihao on 2018-04-24
 *  开发文档： https://developer.qiniu.com/kodo/sdk/1289/nodejs
 *             https://developer.qiniu.com/kodo/sdk/3828/node-js-v6
 */

let express = require('express');
let router = express.Router();
let qiniu = require('qiniu');
let cryptoJS = require('crypto-js');

let util = require('../util');
const db = require('../conf');

//  七牛密钥
let accessKey = 'R0Y_KnkPB9LQewBGr3R5h90j_kIvq6JFliD5ghiU';
let secretKey = 'xj9ALSOfd0V5wl8kCkFakay5j_QL8KR_fUDPLSSn';
let mac = new qiniu.auth.digest.Mac(accessKey,secretKey);

let options = {
    scope: 'byjs',
    expires: 7200
};

router.get('/', function(req, res, next) {
    res.render('qi-niu-upload',{title: '七牛上传'});
});

/* GET users listing. */
router.post('/getToken', function(req, res, next) {

    // 并不是简单的对称加密
    let putPolicy = new qiniu.rs.PutPolicy(options);
    let uploadToken = putPolicy.uploadToken(mac);

    res.send({token:uploadToken});
});

// 通过hash 获取图片url (不成功的)
router.post('/getImageUrl',function(req, res, next) {

    let imageName = '0.png';

    // 获取当前时间戳(Unix timestamp 单位秒)
    let newTime = Math.round(new Date().getTime()/1000)
    let expires = parseInt( newTime+60*60 );  // expires 表示url的过期时间

    // 临时域名  'http://p9iorfda5.bkt.clouddn.com/1.png'
    let domain = 'http://p875wqykn.bkt.clouddn.com/';

    // 构造url
    let DownloadUrl = domain + imageName + '?e=' + expires;



    // 进行HMAC-SHA1(哈希运算消息验证码 Hash-based Message Authentication Code )
    // HMAC运算利用哈希算法， 以一个密钥和消息输入，生成一个消息密钥，用于验证消息的完整性和消息的真实性
    let bySign = cryptoJS.HmacSHA1(DownloadUrl, secretKey);

    // URL安全的base64编码
    let EncodedBySign = util.urlsafe_base64_encode(bySign);

    // 将访问密钥（AccessKey）和上面生成的认证拼接形成token
    let Token = accessKey + ':' + EncodedBySign;

    // 生成url
    let URL = domain + imageName+ "?e=" + expires +'&token='+ Token;

    //返回数据
    res.send({
        code: 0,
        success: true,
        message: '获取图片URL',
        data: {
            url: URL
        }
    })

});

/***
 *  图片上传成功后，将hash和key 返回给后后台，
 *  将数据保存到数据库
 */
router.post('/qiniu', function(req, res, next){

    const params = req.body;
    let key = params.key;

    // 检验是否存在当前hash
    const checkSql = 'SELECT * FROM by_image_hash WHERE hashCode=?';
    db(checkSql,[params.hash]).then(data =>{
       if(data.length === 0){
           if(params.hash && params.key){
               let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
               let config = new qiniu.conf.Config();
               let bucketManager = new qiniu.rs.BucketManager(mac, config);
               let privateBucketDomain = 'http://p875wqykn.bkt.clouddn.com';
               let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
               let privateDownloadUrl = bucketManager.privateDownloadUrl(privateBucketDomain, key, deadline);

               // 拼接sql
               const sql = 'INSERT INTO by_image_hash (hashCode,keyCode,urlCode) VALUES (?)';
               const tempArr = [params.hash,params.key,privateDownloadUrl];

               //保存到数据库
               db(sql,[tempArr]).then( res => {
                   console.log('保存image结果', 'gogoog')
               });

               res.send({
                   code: 0,
                   success: true,
                   message: '成功获取图片的url',
                   data:{
                       url: privateDownloadUrl
                   }
               });
           } else {
               res.send({
                   code: 10003,
                   success: false,
                   message: '没有hash或key',
                   data:{
                       url: ''
                   }
               })
           }
       } else {
           res.send({
               code: 0,
               success: true,
               message: '成功获取图片的url(database)',
               data:{
                   url: data[0].urlCode,
                   downloadUrl: data[0].urlCode + '&attname=' + params.key ,
               }
           });
       }
    });

//

//

// 构建私有空间的链接
//     url = 'http://domain/key';
//     var policy = new qiniu.rs.GetPolicy();

// //生成下载链接url
//     var downloadUrl = policy.makeRequest(url);

// //打印下载的url
//     console.log(downloadUrl);

    /***
     *  创建七牛对象
     *      var qiniu = require("qiniu");
     *  设置是相关配置
     *      qiniu.conf.ACCESS_KEY = 'Access_Key';
     *      qiniu.conf.SECRET_KEY = 'Secret_Key';
     *  构建私有空间的链接
     *      var url = 'http://domain/key';
     *      var policy = new qiniu.rs.GetPolicy();
     *  生成下载连接
     *      var downloadUrl = policy.makeRequest(url);
     *  创建bucketmanager对象
     *      var client = new qiniu.rs.client();
     *  移动资源
     *      client.move(bucket, key, dstbucket, deskey, function(err, ret) {}
     *  复制资源
     *      client.copy(bucket, key, dstbucket, deskey, function(err, ret) {}
     *   删除资源
     *      client.remove(bucket, key, function(err, ret) {}
     */


});

module.exports = router;